import axios from "axios";
import { ElLoading } from "element-plus";
import router from "@/router/index";


//自定义axios
const instance =axios.create({
    //后端开发人员提供的测试或开发环境接口地址
    baseURL:'http://localhost:3001/admin'
})

// 从cookie中获取token的函数
function getTokenFromCookie(): string {
    const cookieArr = document.cookie.split(';')
    for (let i = 0; i < cookieArr.length; i++) {
        const cookieItem = cookieArr[i]
        if (!cookieItem) continue
        
        const cookiePair = cookieItem.split('=')
        if (cookiePair && cookiePair.length > 0 && cookiePair[0] && cookiePair[0].trim() === 'authToken') {
            return cookiePair.length > 1 && cookiePair[1] ? decodeURIComponent(cookiePair[1]) : ''
        }
    }
    return ''
}

instance.interceptors.request.use((config)=>{
    // 从cookie获取token
    const token = getTokenFromCookie();
    if (token) {
        config.headers.token = token;
    }
    return config;
},(err)=>{
    return Promise.reject(err);
})

// 请求响应的拦截器
instance.interceptors.response.use((response) => {
  if (response.data.code === '10119' || response.data.code === 401) {
    // 清除cookie中的token
    document.cookie = 'authToken=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;'
    router.push('/login')
    return response
  } else {
    return response
  }

}, (err) => {
  // 处理网络错误或超时等情况
  console.error('请求错误:', err)
  return Promise.reject(err)
})

export default instance;

